package com.atguigu.gulimall.Auth.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResp;
import com.atguigu.gulimall.Auth.feign.MemberFeignService;
import com.atguigu.gulimall.Auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class Outh2Controller {

      @Autowired
      MemberFeignService memberFeignService;


      @RequestMapping("/oauth2.0/weibo/success")
       public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

             Map<String, String> map = new HashMap<>();
             map.put("client_id","2077705774");
             map.put("client_secret","40af02bd1c7e435ba6a6e9cd3bf799fd");
             map.put("grant_type","authorization_code");
             map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
             map.put("code",code);

             //1、根据用户授权返回的code换取access_token
            HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

           // 先判断 请求是否成功
         if(post.getStatusLine().getStatusCode()==200){
             // 把请求获取到的实体 转换为 json
             String responseEntity = EntityUtils.toString(post.getEntity());
             SocialUser socialUser = JSON.parseObject(responseEntity, SocialUser.class);
             //远程调用用户服务 判断 用户是否已经 创建该账户
             R socialLogin = memberFeignService.socialLogin(socialUser);

             if(socialLogin.getCode()==0){
                 MemberResp data = socialLogin.getData("data", new TypeReference<MemberResp>() {});
                   // 实质 存储到redis中去
                   session.setAttribute("loginUser",data);
                 return "redirect:http://gulimall.com";
             }else{
                 return "redirect:http://auth.gulimall.com/login.html";
             }

         }else{
             return "redirect:http://auth.gulimall.com/login.html";
         }

     }





}
